package net.dgg.iboss.sc.backservice.task.service;

import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.sc.backservice.task.constant.CredentialConstant;
import net.dgg.iboss.sc.backservice.task.dao.ProductOrderDao;
import net.dgg.iboss.sc.backservice.task.dao.WarningConfigureDao;
import net.dgg.iboss.sc.backservice.task.dao.credential.BaseCredentialDao;
import net.dgg.iboss.sc.backservice.task.dao.credential.GeneralCertificateDao;
import net.dgg.iboss.sc.backservice.task.dao.credential.StorageCapacityDao;
import net.dgg.iboss.sc.backservice.task.entity.*;
import net.dgg.iboss.sc.backservice.task.entity.credentail.BaseCredential;
import net.dgg.iboss.sc.backservice.task.entity.credentail.CertificateSpecialty;
import net.dgg.iboss.sc.backservice.task.entity.credentail.GeneralCertificate;
import net.dgg.iboss.sc.backservice.task.util.StringUtils;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import net.dgg.tmd.foundation.platform.treebook.service.TreeBookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 普通证书
 *
 * @author wmj
 * @date 2018/9/5 0005
 */
@Service
public class GeneralCredentailService {
    private static final String overDueTemplateCode = "ZZSC_ZS_OVER_DUE_V2";
    private static final String unUsedTemplateCode = "ZZSC_ZS_UN_USED";
    private static final String unUsedTreeBookCode = "ZZSC_ZS_UN_USED";
    private static final String overDue = "OVER_DUE";
    private static final String overWarning = "OVER_WARNING";

    @Resource
    private GeneralCertificateDao generalCertificateDao;
    @Resource
    private BaseCredentialDao baseCredentialDao;
    @Resource
    private SystemRecordService systemRecordService;
    @Resource
    private CertificateSpecialtyService certificateSpecialtyService;
    @Resource
    private StorageCapacityDao storageCapacityDao;
    @Resource
    private UserService userService;
    @Resource
    private ProductOrderDao productOrderDao;
    @Resource
    private ZzInProcessService zzInProcessService;
    @Resource
    private CommonService commonService;
    @Resource
    private WarningConfigureDao warningConfigureDao;
    @Resource
    private TreeBookService treeBookService;

    /**
     * 处理超期证书信息
     */
    @Transactional
    public void dealOverDueGeneralCredentail() throws ParseException {
        System.out.println("-----------------------------------------处理超期证书信息 开始 --------------------------------------------------");
        // 当前日期
        Date now = new Date();

        // 处理超期
        handleOverDue(now);

        // 处理预警
        handleOverWarning(now);

        System.out.println("-----------------------------------------处理超期证书信息 结束 --------------------------------------------------");
    }

    /*
     * @Author zsx
     * @Date 2018-09-06 02:09:08
     * @Description  每天更新资质状态
     */
    @Transactional
    public void updateQualificationOverdueStatus() {
        List<BaseCredential> generalCredentails = baseCredentialDao.findQualificationOverdue(CredentialConstant.ZZ_CREDENTIAL, CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_TWO);
        for (BaseCredential certificate : generalCredentails) {
            certificate.setOverdueStatus(CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_TWO);
            certificate.setUpdaterId(1L);
            certificate.setUpdaterName("超级管理员");
            certificate.setUpdaterOrgId(1L);
            certificate.setUpdateTime(new Date());
            baseCredentialDao.updateBaseByFileds(certificate);
            // 保存操作日志
            SystemRecord systemRecords = new SystemRecord();
            systemRecords.setSource("1");
            systemRecords.setOperateType("2");
            systemRecords.setWorkTableName("zz_base_credential");
            systemRecords.setWorkId(certificate.getId());
            systemRecords.setCertificateCode(certificate.getCertificateNo());
            systemRecords.setSignOrgId(certificate.getSignOrgId());
            systemRecords.setSignOrgName(certificate.getSignOrgName());
            systemRecords.setCertificateType(certificate.getCertificateType());
            systemRecords.setRemarks("修改资质超期状态");
            systemRecordService.apiSave(systemRecords);

            // 如果资质未使用则库容量-1
            if (CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE.equals(certificate.getCertificateStatus())) {
                List<CertificateSpecialty> certificateSpecialties = certificateSpecialtyService.findCertificateSpecialtyByCertificateId(certificate.getId());
                if (StringUtils.isNotEmpty(certificateSpecialties) && certificateSpecialties.size() > 0) {
                    storageCapacityDao.batchUpdatelibraryNumbers(certificateSpecialties);
                }
            }
        }
    }

    /**
     * 处理超期
     * @param now
     * @throws ParseException
     */
    private void handleOverDue(Date now) throws ParseException {
        // 查询超期的证书
        List<GeneralCertificate> generalCredentails = generalCertificateDao.findOverDueDetail();

        // 三类证书到期
        Boolean certificateToThreeTimeOverDue = null;
        // 证书到期时间
        Boolean certificateExpiryTimeOverDue = null;

        // 人才合同到期时间
        Boolean talentContractExpireTimeOverDue = null;

        // 企业合同到期时间
        Boolean companyContractExpireTimeOverDue = null;

        // 挂靠超期
        Boolean affiliatedExpireTimeOverDue = null;
        Boolean threeAffiliatedExpireTimeOverDue = null;

        // 消息提醒类型
        String warningType = null;

        // 循环处理超期
        for (GeneralCertificate generalCertificate : generalCredentails) {
            String oldOverDueStatus = generalCertificate.getOverdueStatus();
            String oldOverDueType = generalCertificate.getOverdueType();

            warningType = "";

            // 判断超期类型
            certificateToThreeTimeOverDue = (StringUtils.isNotEmpty(generalCertificate.getCertificateToThreeTime()) && (DateUtil.daysBetween(generalCertificate.getCertificateToThreeTime(), now) > 0)) ? false : true;
            certificateExpiryTimeOverDue = StringUtils.isNotEmpty(generalCertificate.getCertificateExpiryTime()) && DateUtil.daysBetween(generalCertificate.getCertificateExpiryTime(), now) > 0 ? false : true;

            talentContractExpireTimeOverDue = StringUtils.isNotEmpty(generalCertificate.getTalentContractExpireTime()) && DateUtil.daysBetween(generalCertificate.getTalentContractExpireTime(), now) > 0 ? false : true;

            companyContractExpireTimeOverDue = StringUtils.isNotEmpty(generalCertificate.getCompanyContractExpireTime()) && DateUtil.daysBetween(generalCertificate.getCompanyContractExpireTime(), now) > 0 ? false : true;

            affiliatedExpireTimeOverDue = StringUtils.isNotEmpty(generalCertificate.getAffiliatedExpireTime()) && DateUtil.daysBetween(generalCertificate.getAffiliatedExpireTime(), now) > 0 ? false : true;
            threeAffiliatedExpireTimeOverDue = StringUtils.isNotEmpty(generalCertificate.getThreeAffiliatedExpireTime()) && DateUtil.daysBetween(generalCertificate.getThreeAffiliatedExpireTime(), now) > 0 ? false : true;

            if (certificateToThreeTimeOverDue && certificateExpiryTimeOverDue && talentContractExpireTimeOverDue && companyContractExpireTimeOverDue && affiliatedExpireTimeOverDue) {
                // 都没有超期
                generalCertificate.setOverdueType(null);
                generalCertificate.setOverdueStatus("1");
            } else {
                StringBuffer overDueType = new StringBuffer();
                if (!certificateToThreeTimeOverDue || !certificateExpiryTimeOverDue) {
                    // 证书超期或者三类证书超期
                    warningType += "证书,";
                    overDueType.append(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL + ",");
                }
                if (!talentContractExpireTimeOverDue) {
                    // 人才合同到期
                    warningType += "人才合同,";
                    overDueType.append(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_TALENTS + ",");
                }
                if (!companyContractExpireTimeOverDue) {
                    // 企业合同到期
                    warningType += "企业合同,";
                    overDueType.append(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_COMPANY + ",");
                }

                if (!affiliatedExpireTimeOverDue || !threeAffiliatedExpireTimeOverDue) {
                    // 挂靠超期
                    overDueType.append(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_AFFILIATED + ",");
                }

                generalCertificate.setOverdueType(overDueType.toString());
                generalCertificate.setOverdueStatus("0");
            }

            // 更新超期信息
            generalCertificate.setUpdaterId(1L);
            generalCertificate.setUpdaterName("超级管理员");
            generalCertificate.setUpdaterOrgId(1L);
            baseCredentialDao.updateByFileds(generalCertificate);
            generalCertificateDao.updateByFileds(generalCertificate);

            // 如果没有过期类型或者当前过期类型不等于之前的过期类型，保存操作日志
            if (StringUtils.isEmpty(oldOverDueType) || !oldOverDueStatus.equals(generalCertificate.getOverdueStatus())) {
                SystemRecord systemRecords = new SystemRecord();
                systemRecords.setSource("1");
                systemRecords.setOperateType("2");
                systemRecords.setWorkTableName("zz_general_certificate");
                systemRecords.setWorkId(generalCertificate.getId());
                systemRecords.setCertificateCode(generalCertificate.getCertificateNo());
                systemRecords.setSignOrgId(generalCertificate.getSignOrgId());
                systemRecords.setSignOrgName(generalCertificate.getSignOrgName());
                systemRecords.setCertificateType(generalCertificate.getCertificateType());
                systemRecords.setCertificateCode(generalCertificate.getCertificateNo());
                systemRecords.setCertificateName(generalCertificate.getCertificateName());
                systemRecords.setRemarks("证书中心：修改证书超期状态");
                systemRecordService.apiSave(systemRecords);
            }

            // 之前证书状态为未超期，更改后超期，则库存减少
            // 更改前的证书状态为证书超期则已经减少过库容，不需要重复加减库容
            // 证书之前状态为超期，但是不包含证书超期，之后证书超期也需要减去在库容量
            if ("1".equals(oldOverDueStatus) || ("0".equals(oldOverDueStatus) && !oldOverDueType.contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL))) {
                // 如果证书未使用并且未出库则库容量-1
                if (CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN.equals(generalCertificate.getLibraryStatus()) && CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE.equals(generalCertificate.getCertificateStatus())) {
                    if ("0".equals(generalCertificate.getOverdueStatus()) && generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL)) {
                        List<CertificateSpecialty> certificateSpecialties = certificateSpecialtyService.findCertificateSpecialtyByCertificateId(generalCertificate.getId());
                        if (StringUtils.isNotEmpty(certificateSpecialties) && certificateSpecialties.size() > 0) {
                            storageCapacityDao.batchUpdatelibraryNumbers(certificateSpecialties);
                        }
                    }
                }
            }


            // 消息推送
            if (StringUtils.isNotEmpty(generalCertificate.getScOrderId())) {
                // 查询生产订单
                ProductOrder productOrder = productOrderDao.selectByPrimaryKey(generalCertificate.getScOrderId());
                if (productOrder != null) {
                    // 证书到期
                    pushExpire(generalCertificate, productOrder, now, overDue, certificateToThreeTimeOverDue, certificateExpiryTimeOverDue);
                    // 人才合同到期
                    pushTalentContract(generalCertificate, productOrder, now, overDue, talentContractExpireTimeOverDue);
                    // 企业合同到期
                    pushCompanyContract(generalCertificate, productOrder, now, overDue, companyContractExpireTimeOverDue);
                    // 证书超期
                    pushAffilated(generalCertificate, productOrder, now, overDue, affiliatedExpireTimeOverDue);
                }
            }
        }
    }

    /**
     * 处理预警
     * @param now
     * @throws ParseException
     */
    private void handleOverWarning(Date now) throws ParseException {
        // 查询每个事业部的预警配置
        Map<String, Object> map = new HashMap<>();
        map.put("warningType", CredentialConstant.GENERAL_CREDENTIAL);
        List<WarningConfigure> warningConfigures = warningConfigureDao.selectWarningConfig(map);
        Map<Long, WarningConfigure> warningConfigureMap = warningConfigures.stream().collect(Collectors.toMap(WarningConfigure::getSignOrgId, v -> v, (v1, v2) -> v2));

        // 总共未使用预警的证书数量
        int unUsedCertificateCount = 0;

        // 按照事业部进行预警处理
        for (Map.Entry<Long, WarningConfigure> entry : warningConfigureMap.entrySet()) {
            Long orgId = entry.getKey();
            WarningConfigure configure = entry.getValue();

            // 查询预警的证书
            Map<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            params.put("affiliatedExpireTime", configure.getCertificateHangUpWarning());
            params.put("threeAffiliatedExpireTime", configure.getCertificateHangUpWarning());
            params.put("companyContractExpireTime", configure.getCompanyContractWarning());
            params.put("talentContractExpireTime", configure.getTalentContractWarning());
            params.put("certificateToThreeTime", configure.getCertificateExpireWarning());
            params.put("certificateExpiryTime", configure.getCertificateExpireWarning());
            params.put("lastUserTime", configure.getCertificateNotUsedWarning());
            List<GeneralCertificate> generalCertificates = generalCertificateDao.findOverWarningDetail(params);

            // 循环预警
            for (GeneralCertificate generalCertificate : generalCertificates) {
                // 关联的生产订单
                ProductOrder productOrder = productOrderDao.selectByPrimaryKey(generalCertificate.getScOrderId());

                // 判断预警类型
                Boolean certificateToThreeTimeOverDue = StringUtils.isEmpty(generalCertificate.getCertificateToThreeTime())
                        || (DateUtil.daysBetween(generalCertificate.getCertificateToThreeTime(), now) > 0)
                        || (DateUtil.daysBetween(generalCertificate.getCertificateToThreeTime(), now) < configure.getTalentContractWarning());
                Boolean certificateExpiryTimeOverDue = StringUtils.isEmpty(generalCertificate.getCertificateExpiryTime())
                        || (DateUtil.daysBetween(generalCertificate.getCertificateExpiryTime(), now) > 0)
                        || (DateUtil.daysBetween(generalCertificate.getCertificateExpiryTime(), now) < configure.getTalentContractWarning());

                Boolean talentContractExpireTimeOverDue = StringUtils.isEmpty(generalCertificate.getTalentContractExpireTime())
                        || DateUtil.daysBetween(generalCertificate.getTalentContractExpireTime(), now) > 0
                        || (DateUtil.daysBetween(generalCertificate.getTalentContractExpireTime(), now) < configure.getTalentContractWarning());

                Boolean companyContractExpireTimeOverDue = StringUtils.isEmpty(generalCertificate.getCompanyContractExpireTime())
                        || DateUtil.daysBetween(generalCertificate.getCompanyContractExpireTime(), now) > 0
                        || (DateUtil.daysBetween(generalCertificate.getCompanyContractExpireTime(), now) < configure.getTalentContractWarning());

                Boolean affiliatedExpireTimeOverDue = StringUtils.isEmpty(generalCertificate.getAffiliatedExpireTime())
                        || DateUtil.daysBetween(generalCertificate.getAffiliatedExpireTime(), now) > 0
                        || (DateUtil.daysBetween(generalCertificate.getAffiliatedExpireTime(), now) < configure.getTalentContractWarning());
                Boolean threeAffiliatedExpireTimeOverDue = StringUtils.isEmpty(generalCertificate.getThreeAffiliatedExpireTime())
                        || DateUtil.daysBetween(generalCertificate.getThreeAffiliatedExpireTime(), now) > 0
                        || (DateUtil.daysBetween(generalCertificate.getThreeAffiliatedExpireTime(), now) < configure.getTalentContractWarning());
                Boolean lastUserTimeOverDue = StringUtils.isEmpty(generalCertificate.getLastUserTime())
                        || (DateUtil.daysBetween(generalCertificate.getLastUserTime(), now) < configure.getCertificateNotUsedWarning());

                // 计算未使用超期的数量
                if(!lastUserTimeOverDue){
                    ++ unUsedCertificateCount;
                }

                // 推送预警消息
                // 证书到期预警
                pushExpire(generalCertificate, productOrder, now, overWarning, certificateToThreeTimeOverDue, certificateExpiryTimeOverDue);
                // 人才合同到期预警
                pushTalentContract(generalCertificate, productOrder, now, overWarning, talentContractExpireTimeOverDue);
                // 企业合同到期预警
                pushCompanyContract(generalCertificate, productOrder, now, overWarning, companyContractExpireTimeOverDue);
                // 证书超期预警
                pushAffilated(generalCertificate, productOrder, now, overWarning, affiliatedExpireTimeOverDue);
            }
        }

        // 推送未使用预警
        pushUnUsed(unUsedCertificateCount);
    }

    /**
     * 推送证书到期（您好，您的客户{0}商机为{1}，{2}的{3}证书{4}，请及时联系客户处理。）（您好，您的客户xxx商机为SJ001，张三的建造师证书使用已到期10天，请及时联系客户处理。）
     * @param generalCertificate
     * @param productOrder
     * @param certificateToThreeTimeOverDue
     * @param certificateExpiryTimeOverDue
     * @throws ParseException
     */
    private void pushExpire(GeneralCertificate generalCertificate, ProductOrder productOrder, Date now, String overType, Boolean certificateToThreeTimeOverDue, Boolean certificateExpiryTimeOverDue) throws ParseException {
        if(certificateExpiryTimeOverDue && certificateToThreeTimeOverDue){
            return;
        }

        UserEntity user = userService.findUserById(productOrder.getSignUserId());
        List<UserEntity> users = new ArrayList<>();
        users.add(user);

        List<String> args = new ArrayList<>();
        args.add(productOrder.getCustomerName());
        args.add(productOrder.getBusinessNo());
        args.add(generalCertificate.getPersonalName());
        args.add(generalCertificate.getCertificateType());

        StringBuffer result = new StringBuffer();
        if(overDue.equals(overType)){
            // 超期提醒
            if(!certificateExpiryTimeOverDue){
                result.append("已到期" + Math.abs(DateUtil.daysBetween(generalCertificate.getCertificateExpiryTime(), now)) + "天，");
            }
            if(!certificateToThreeTimeOverDue){
                result.append("三类证书已到期" + Math.abs(DateUtil.daysBetween(generalCertificate.getCertificateToThreeTime(), now)) + "天，");
            }
        }
        if(overWarning.equals(overType)){
            // 预警
            if(!certificateExpiryTimeOverDue){
                result.append("过期剩余" + Math.abs(DateUtil.daysBetween(generalCertificate.getCertificateExpiryTime(), now)) + "天，");
            }
            if(!certificateToThreeTimeOverDue){
                result.append("三类证书过期剩余" + Math.abs(DateUtil.daysBetween(generalCertificate.getCertificateToThreeTime(), now)) + "天，");
            }
        }
        args.add(result.toString());

        commonService.sendMsg(users, args.toArray(new String[0]), overDueTemplateCode);
    }

    /**
     * 推送人才合同超期（您好，您的客户{0}商机为{1}，{2}的{3}证书{4}，请及时联系客户处理。）（您好，您的客户xxx商机为SJ001，张三的建造师证书使用已到期10天，请及时联系客户处理。）
     * @param generalCertificate
     * @param productOrder
     * @param now
     * @param talentContractExpireTimeOverDue
     * @throws ParseException
     */
    private void pushTalentContract(GeneralCertificate generalCertificate, ProductOrder productOrder, Date now, String overType, Boolean talentContractExpireTimeOverDue) throws ParseException {
        if(talentContractExpireTimeOverDue){
            return;
        }

        UserEntity user = userService.findUserById(productOrder.getSignUserId());
        List<UserEntity> users = new ArrayList<>();
        users.add(user);

        List<String> args = new ArrayList<>();
        args.add(productOrder.getCustomerName());
        args.add(productOrder.getBusinessNo());
        args.add(generalCertificate.getPersonalName());
        args.add(generalCertificate.getCertificateType());

        if(overDue.equals(overType)){
            args.add("人才证书合同已超期" + Math.abs(DateUtil.daysBetween(generalCertificate.getTalentContractExpireTime(), now)) + "天，");
        }
        if(overWarning.equals(overType)){
            args.add("人才证书合同超期剩余" + Math.abs(DateUtil.daysBetween(generalCertificate.getTalentContractExpireTime(), now)) + "天，");
        }

        commonService.sendMsg(users, args.toArray(new String[0]), overDueTemplateCode);
    }

    /**
     * 推送企业合同超期（您好，您的客户{0}商机为{1}，{2}的{3}证书{4}，请及时联系客户处理。）（您好，您的客户xxx商机为SJ001，张三的建造师证书使用已到期10天，请及时联系客户处理。）
     * @param generalCertificate
     * @param productOrder
     * @param now
     * @param companyContractExpireTimeOverDue
     * @throws ParseException
     */
    private void pushCompanyContract(GeneralCertificate generalCertificate, ProductOrder productOrder, Date now, String overType, Boolean companyContractExpireTimeOverDue) throws ParseException {
        if(companyContractExpireTimeOverDue){
            return;
        }

        UserEntity user = userService.findUserById(productOrder.getSignUserId());
        List<UserEntity> users = new ArrayList<>();
        users.add(user);

        List<String> args = new ArrayList<>();
        args.add(productOrder.getCustomerName());
        args.add(productOrder.getBusinessNo());
        args.add(generalCertificate.getPersonalName());
        args.add(generalCertificate.getCertificateType());
        if(overDue.equals(overType)){
            args.add("企业证书合同已超期" + Math.abs(DateUtil.daysBetween(generalCertificate.getCompanyContractExpireTime(), now)) + "天，");
        }
        if(overWarning.equals(overType)){
            args.add("企业证书合同超期剩余" + Math.abs(DateUtil.daysBetween(generalCertificate.getCompanyContractExpireTime(), now)) + "天，");
        }

        commonService.sendMsg(users, args.toArray(new String[0]), overDueTemplateCode);
    }

    /**
     * 推送证书超期（您好，您的客户{0}商机为{1}，{2}的{3}证书{4}，请及时联系客户处理。）（您好，您的客户xxx商机为SJ001，张三的建造师证书使用已到期10天，请及时联系客户处理。）
     * @param generalCertificate
     * @param productOrder
     * @param now
     * @param affiliatedExpireTimeOverDue
     * @throws ParseException
     */
    private void pushAffilated(GeneralCertificate generalCertificate, ProductOrder productOrder, Date now, String overType, Boolean affiliatedExpireTimeOverDue) throws ParseException {
        if(affiliatedExpireTimeOverDue){
            return;
        }

        UserEntity user = userService.findUserById(productOrder.getSignUserId());
        List<UserEntity> users = new ArrayList<>();
        users.add(user);

        List<String> args = new ArrayList<>();
        args.add(productOrder.getCustomerName());
        args.add(productOrder.getBusinessNo());
        args.add(generalCertificate.getPersonalName());
        args.add(generalCertificate.getCertificateType());
        if(overDue.equals(overType)){
            args.add("已超期" + Math.abs(DateUtil.daysBetween(generalCertificate.getAffiliatedExpireTime(), now)) + "天，");
        }
        if(overWarning.equals(overType)){
            args.add("超期剩余" + Math.abs(DateUtil.daysBetween(generalCertificate.getAffiliatedExpireTime(), now)) + "天，");
        }

        commonService.sendMsg(users, args.toArray(new String[0]), overDueTemplateCode);
    }

    /**
     * 推送未使用的消息（您好，截止当前证书系统中超过未使用预警天数的未使用证书共计{0}本，比上周{1}本，请您知晓。）（您好，截止当前证书系统中超过未使用预警天数的未使用证书共计xxxx本，比上周新增/减少x本，请您知晓。）
     * @param unUsedCertificateCount
     */
    private void pushUnUsed(int unUsedCertificateCount) {
        // 获取配置的数据
        TreeBook book = treeBookService.getTreeBookByCode(unUsedTreeBookCode);
        String loginName = book.getExt1();
        Integer oldCount = Integer.valueOf(book.getExt2());

        UserEntity user = userService.findUserByLoginName(loginName);
        List<UserEntity> users = new ArrayList<>();
        users.add(user);

        List<String> args = new ArrayList<>();
        args.add(String.valueOf(unUsedCertificateCount));
        if(unUsedCertificateCount >= oldCount){
            args.add("新增" + (unUsedCertificateCount - oldCount));
        }
        if(unUsedCertificateCount < oldCount){
            args.add("减少" + (oldCount - unUsedCertificateCount));
        }

        commonService.sendMsg(users, args.toArray(new String[0]), unUsedTemplateCode);
    }
}
